#include "Account.h"
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
// 账户类构造函数，初始化账户ID、所有者姓名和初始余额
Account::Account(const string &id, const string &owner, double initialBalance)
    : accountId(id), ownerName(owner), balance(initialBalance)
{
}

// 获取账户ID
string Account::getAccountId() const
{
    return accountId;
}

// 获取账户所有者姓名
string Account::getOwnerName() const
{
    return ownerName;
}

// 获取账户余额
double Account::getBalance() const
{
    return balance;
}

// 获取账户交易记录列表
const vector<shared_ptr<Transaction>> &Account::getTransactions() const
{
    return transactions;
}

// 添加交易记录到账户
void Account::addTransaction(const shared_ptr<Transaction> &transaction)
{
    transactions.push_back(transaction);
}

// 更新账户余额
void Account::updateBalance(double amount)
{
    balance += amount;
}

// 生成账户报告并保存到文件
void Account::generateAccountReport(const string &filename) const
{
    // 打开输出文件流
    ofstream reportFile(filename);

    // 检查文件是否成功打开
    if (!reportFile.is_open())
    {
        cerr << "Error: Unable to create report file: " << filename << endl;
        return;
    }

    // 写入账户基本信息
    reportFile << "===== Account Transactions Report =====" << endl;
    reportFile << "Account ID: " << accountId << endl;
    reportFile << "Account Type: " << getAccountType() << endl;
    reportFile << "Owner: " << ownerName << endl;
    reportFile << "Current Balance: ¥" << fixed << setprecision(2) << balance << endl;
    reportFile << "Transaction Count: " << transactions.size() << endl;
    reportFile << "==============================================" << endl
               << endl;

    // 检查是否有交易记录
    if (transactions.empty())
    {
        reportFile << "No transactions found for this account." << endl;
    }
    else
    {
        // 写入交易历史记录标题
        reportFile << "Transaction History (chronological order):" << endl
                   << endl;

        // 按时间戳对交易记录进行排序
        vector<shared_ptr<Transaction>> sortedTransactions = transactions;
        sort(sortedTransactions.begin(), sortedTransactions.end(),
                  [](const shared_ptr<Transaction> &a, const shared_ptr<Transaction> &b)
                  {
                      return a->getTimestamp() < b->getTimestamp();
                  });

        // 遍历并输出每条交易记录
        for (const auto &transaction : sortedTransactions)
        {
            reportFile << "---------------------------------------------" << endl;
            reportFile << transaction->toString() << endl;
        }
    }

    // 关闭文件并显示成功信息
    reportFile.close();
    cout << "Report successfully generated as \"" << filename << "\"" << endl;
}